package com.mmf.utils;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Created by MMF on 2017-10-18.
 */
public class UploadImage {
    /**
     * 多文件上传
     ***/
    public static void uploadImage(int id, MultipartHttpServletRequest request, LoadSuccess loadSuccess) {
        Iterator iter = request.getFileNames();
        while (iter.hasNext()) {
            //一次遍历所有文件
            List<MultipartFile> files = request.getFiles(iter.next().toString());
            LoadSuccess mLoadSuccess = loadSuccess;
            //图片命名
            long time = System.currentTimeMillis();
            String filePath = request.getSession().getServletContext().getRealPath("/") + "/upload/";
            (new File(filePath)).mkdirs();
            if (files != null && files.size() > 0) {
                for (MultipartFile file : files) {
                    String pathTemp = Md5.getMD5Code(time + file.getOriginalFilename()) + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") - 1, file.getOriginalFilename().length());
                    String path = filePath + pathTemp;
                    //上传
                    try {
                        file.transferTo(new File(path));
                        //在数据库中插入一个记录
                        mLoadSuccess.insertDate(pathTemp,id,Integer.parseInt(file.getName()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    public interface LoadSuccess {
        void insertDate(String path, int id, int type);
    }
}
